
const router = require('koa-router')();
const tools = require('../../module/tools.js');
const DB = require('../../module/db.js');
const svgCaptcha = require('svg-captcha');

router.get('/', async (ctx) => {

    await ctx.render('admin/login');
});

router.post('/', async (ctx) => {

	//ctx.request.body
	let username = ctx.request.body.username;
	let pass = ctx.request.body.password;
	let code = ctx.request.body.code;
	
	
	// 验证码判断
	if(code.toLocaleLowerCase() !== ctx.session.code.toLocaleLowerCase()){
		ctx.render('admin/error', {
			message: '验证码错误。',
			redirectUrl: ctx.state.__HOST__ + '/admin/login'
		});
		return;
	}
	
	
	let result = await DB.findOne('admin', {
		username: username,
		password: tools.md5(pass)
	});
	
	
	if(!result || result.length <= 0){
		ctx.render('admin/error', {
			message: '用户名或密码错误。',
			redirectUrl: ctx.state.__HOST__ + '/admin/login'
		});
		return;
	}
	
	// 信息写入session
	ctx.session.userinfo = result[0];
	
	
	// 更新用户表，该表用户登录时间
	await DB.updateOne('admin', {
		_id: DB.getObjectID(result[0]._id)
	}, {
		last_time: new Date()
	})
	
	ctx.redirect(ctx.state.__HOST__ + '/admin');
});


/**
 * 验证码路由
 */
router.get('/code', async (ctx) => {
	
//	let captcha = svgCaptcha.create({
//		size: 4,
//		fontSize: 50,
//		width: 100,
//		height: 40,
//		background: '#cc9966'
//	});

	let captcha = svgCaptcha.createMathExpr({
		size: 6,
		fontSize: 50,
		width: 120,
		height: 34,
		background: '#cc9966'
	});
    
    //验证码存入session
    ctx.session.code = captcha.text;
    
    // 设置响应头
    ctx.response.type = 'image/svg+xml';
    ctx.body = captcha.data;
});



router.get('/loginOut', async (ctx) => {

    ctx.session.userinfo = null;
    ctx.redirect(ctx.state.__HOST__ + '/admin/login');
});


module.exports = router.routes();